<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\func\Lib;
use app\common\func\Tools;
use app\common\model\PolicyRelation;
use fast\Tree;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 机构
 *
 * @icon fa fa-circle-o
 */
class Company extends Backend
{

    /**
     * Company模型对象
     * @var \app\common\model\Company
     */
    protected $model = null;

    protected $child = [];

    protected $companyInfo = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Company;
        $this->view->assign("statusList", $this->model->getStatusList());

        if(!$this->auth->isSuperAdmin()){
            $this->companyInfo = $this->auth->getCompany();

            if($this->companyInfo){
                $list = Tree::instance()->init(collection(\app\common\model\Company::select())->toArray())->getChildrenIds($this->companyInfo->id);
                $this->child = $list;
            }
        }
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $query = $this->model->with(['level']);

            if(!$this->auth->isSuperAdmin()){
                $query->where("company.id","in",$this->child);
            }

            $list = $query->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','pid','name','level_id','product_ids','contact_name','contact_phone','status','is_setting','create_time']);
                $row->visible(['level']);
				$row->getRelation('level')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            if($this->auth->isSuperAdmin()){
                $pid = 0;
                $companyLevel = Lib::getCompanyLevelByPid(0);
            }else{
                if($this->companyInfo){
                    $pid = $this->companyInfo->id;
                }else{
                    $this->error(__('您未绑定机构，请绑定后操作！'));
                }
                $company = $this->auth->getCompany();
                $companyLevel = Lib::getCompanyLevelByPid($company->level_id);
            }
            if(!$companyLevel){
                $this->error(__('您已是最低级别，无法创建！'));
            }
            $params['pid'] = $pid;
            $params['level_id'] = $companyLevel->id;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function qr($ids){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->view->assign("id",$ids);
        return $this->view->fetch();
    }

    public function setting($ids){
        $row = $this->model->get($ids);
        if (false === $this->request->isPost()) {

            if(!$this->auth->isSuperAdmin()){
                $product = Lib::getUserProduct(1,$this->auth->getCompany()->id);
            }else{
                $product = \app\common\model\Product::where(["status" => 1])->select();
            }

            if($this->auth->isSuperAdmin()){
                $mainType = 0;
                $mainId = 0;
            }else{
                $mainType = 1;
                $mainId = $this->auth->getCompany()->id;
            }
            if (count($product) > 0) {
                foreach ($product as $key => &$val) {
                    $val['policy'] = Lib::getPolicyByProduct($mainType, $mainId, $val['id']);
                    $default = Lib::getDefaultPolicy(1, $row->id, $val['id']);
                    $val['default'] = $default ? 1 : 0;
                }
                unset($val);
            }

            $this->view->assign("product",$product);
            $this->assignconfig("company",$ids);
            return $this->view->fetch();
        }

        $policyId = $this->request->post("policy_id");
        $productId = $this->request->post("product_id");

        $result = false;
        Db::startTrans();
        try {
            PolicyRelation::where(["main_type" => 1,"main_id" => $ids,"product_id" => $productId])->update(["default" => 0]);

            $relation = Lib::getPolicyRelation(1,$ids,$productId,$policyId);
            if(!$relation){
                $relation = new PolicyRelation();
            }
            $relation->main_type = 1;
            $relation->main_id = $ids;
            $relation->product_id = $productId;
            $relation->policy_id = $policyId;
            $relation->default = 1;
            $relation->default_time = time();
            $relation->save();

            $row->is_setting = 1;
            $result = $row->save();
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success("操作成功！");
    }

    public function policy($ids){
        if (false === $this->request->isPost()) {
            $product = Lib::getUserProduct(1, $ids);

            if (count($product) > 0) {
                foreach ($product as $key => &$val) {
                    $val["policy"] = Lib::getUserPolicy(1, $ids, $val['id']);
                }
                unset($val);
            }

            $this->view->assign("product",$product);
            $this->assignconfig("company",$ids);
            return $this->view->fetch();
        }

        $relationId = $this->request->post("relation_id");
        $productId = $this->request->post("product_id");

        $stock = Lib::getStocks(1,$ids,$productId);
        if($stock && $stock->stocks != 0){
            $this->error("机构库存未清，不允许调整政策！");
        }

        $childCompany = Tools::getCompanyChild($ids,3);//查询所有下级机构
        if(count($childCompany) > 0){
            foreach ($childCompany as $key => $val){
                $childStock = Lib::getStocks(1,$val['id'],$productId);
                if($childStock && $childStock->stocks != 0){
                    $this->error("机构下级【{$val['name']}】库存未清，不允许调整政策！");
                }
                $directUser = Tools::getCompanyChildUser($val['id']);//查询下级机构的直属代理
                if(count($directUser) > 0){
                    foreach ($directUser as $k => $v){
                        $directStock = Lib::getStocks(2,$v['id'],$productId);
                        if($directStock && $directStock->stocks != 0){
                            $this->error("机构下级【{$v['name']}】库存未清，不允许调整政策！");
                        }
                        $childUser = Tools::getUserChild($v['id'],3);//查询直属代理的所有下级代理
                        if(count($childUser) > 0){
                            foreach ($childUser as $ks => $vs){
                                $userStock = Lib::getStocks(2,$vs['id'],$productId);
                                if($userStock && $userStock->stocks != 0){
                                    $this->error("机构下级【{$vs['name']}】库存未清，不允许调整政策！");
                                }
                            }
                        }
                    }
                }
            }
        }

        $result = false;
        Db::startTrans();
        try {
            PolicyRelation::where(["main_type" => 1,"main_id" => $ids,"product_id" => $productId])->update(["default" => 0]);

            $relation = PolicyRelation::get($relationId);
            $relation->default = 1;
            $relation->default_time = time();
            $result = $relation->save();
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success("操作成功！");
    }
}
